package com.baiyu.service;

import com.baiyu.netty.MocServerInitializer;
import com.baiyu.netty.MocWebsocketInitializer;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class NettyService {
    /**
     * netty服务监听端口
     */
    @Value("${netty.port:8007}")
    private int port;

    @Value("${netty.websocket.port:8006}")
    private int webSocketPort;

    public void start(ApplicationContext applicationContext) throws InterruptedException {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            // 2. 启动 protobuf 服务（8007端口）
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 1024) //已经守
                    .childOption(ChannelOption.SO_RCVBUF, 1024 * 1024 * 50) // 接收缓冲区50MB
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .childHandler(applicationContext.getBean(MocServerInitializer.class));

            // 2. 启动 WebSocket 服务（8006端口）
            ServerBootstrap websocketBootstrap = new ServerBootstrap();
            websocketBootstrap.group(bossGroup, workerGroup) // 共享线程池
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 1024) //已经守
                    .childOption(ChannelOption.SO_RCVBUF, 1024 * 1024 * 50) // 接收缓冲区50MB
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .childHandler(applicationContext.getBean(MocWebsocketInitializer.class)); // WebSocket 初始化器
            log.info("Netty started on port: {} (TCP) ", this.port);
            log.info("Netty started on port: {} (Websocket) ", this.webSocketPort);
            ChannelFuture f = b.bind(port).sync();
            ChannelFuture websocketFuture = websocketBootstrap.bind(webSocketPort).sync();

            f.channel().closeFuture().sync();
            websocketFuture.channel().closeFuture().sync();
        } finally {
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }

    }

}
